import traceback

from fastapi import Depends, HTTPException, status

from app.auth.cruds.api import ApiCRUD
from app.auth.models.api import ApiCreate
from app.core.handlers.database import SessionDep
from app.core.handlers.loggers import logger
from app.core.handlers.response import SuccessResponse


class ApiService:
    def __init__(self, db: SessionDep, api_crud: ApiCRUD = Depends()):
        self.db = db
        self.api_crud = api_crud

    async def create_api(self, api_data: ApiCreate):
        try:
            api_exist = await self.api_crud.get_api_by_code(api_data.code)
            if api_exist:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST, detail="Api已经存在"
                )
            new_api = await self.api_crud.create_api(api_data)
            self.db.commit()
            self.db.refresh(new_api)
            return SuccessResponse(message="创建成功")

        except Exception as e:
            self.db.rollback()
            logger.error(traceback.format_exc())
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"发生错误: {str(e)}",
            )
